//
//  DTLanguageManager.m
//  DayToDo
//
//  Created by karry on 2021/2/18.
//

#import "DTLanguageManager.h"

@interface DTLanguageManager()

@property (nonatomic, strong) NSString *laguageType;

@property (nonatomic, strong) NSBundle *bundle;


@end

@implementation DTLanguageManager

singleton_implementation(DTLanguageManager)

//
//NSString *laguageType =[NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"]];
////在文件目录中确认多语言类型对应的路径
//NSString *path = [[NSBundle mainBundle] pathForResource:laguageType ofType:@"lproj"];
////在多语言文件中查找label对应的值
//NSString *labelText = [[NSBundle bundleWithPath:path] localizedStringForKey:@"label" value:nil ta

- (BOOL)isChinese{
    if ([self.laguageType hasPrefix:@"zh"]) {
        return YES;
    }
    return NO;
}
- (BOOL)isJapanese{
    if ([self.laguageType hasPrefix:@"ja"]) {
        return YES;
    }
    return NO;
}

- (BOOL)isKorean{
    if ([self.laguageType hasPrefix:@"ko"]) {
        return YES;
    }
    return NO;
}
- (instancetype)init{
    if (self = [super init]) {
        [self update];
    }
    return self;
}

- (void)update{
    
    NSString *laguageType = [[NSUserDefaults standardUserDefaults]objectForKey:@"KeyLaguageType"];
    
    if (laguageType.length == 0) {
        laguageType = [NSLocale preferredLanguages].firstObject;
        if ([laguageType hasPrefix:@"zh"]) {
            laguageType = @"zh-Hans";
        }else if ([laguageType hasPrefix:@"ja"]) {
            laguageType = @"ja";
        }else if ([laguageType hasPrefix:@"ko"]) {
            laguageType = @"ko";
        }else{
            laguageType = @"en";
        }
    }
    self.laguageType = laguageType;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:self.laguageType ofType:@"lproj"];
    
    if (path == nil) {
        path = [[NSBundle mainBundle]pathForResource:@"en" ofType:@"lproj"];
    }
    
    NSBundle *bundle = [NSBundle bundleWithPath:path];
    self.bundle = bundle;

    
}

- (NSString *)stingWithKey:(NSString *)key{
    NSString *string = [self.bundle localizedStringForKey:key value:nil table:@"Localizable"];
    if (string.length == 0) {
        string = key;
    }
    return string;
}

@end
